<meta charset="utf-8">
<link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
<script src="lib/vue.js"></script>
<script src="lib/jquery.js"></script>
<script src="lib/RongIMLib-2.2.6.min.js"></script>
<script src="lib/RongEmoji-2.2.4.min.js"></script>
<script src="lib/RongIMVoice-2.2.4.min.js"></script>



<div class="container" id="app">
    <div class="row">
        <h3>聊天室<small>老师端</small></h3>
    </div>
    <div class="row">
        <br>
        <div class="col-md-8 col-md-offset-2">
            <div style="width: 810px">
                <div v-show="!isJoin">
                    <input class="form-control" v-model="name" placeholder="老师用户名">
                    <button class="btn btn-default" @click="connect()" >连接</button>
                </div>

                <div v-show="isJoin" class="chat-box">
                    <div class="message-editor">
                        <textarea class="form-control" v-model="sendMsg.words" placeholder="熟人文本"></textarea>
                        <button @click="send(4)">发送</button>
                    </div>

                    <div class="chat-message">
                        <ul>
                            <li v-for="a in logs">{{a}}</li>
                        </ul>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
    const AppKey = 'pwe86ga5phdt6';
    const TokenUrl = 'http://live.me/admin/teachers/chat_login';

    var app = new Vue({
        el: "#app",
        data: {
            token: '',
            name: '',
            logs: [
                "欢迎： @"+new Date().toLocaleString()
            ],
            isJoin: false,
            sendMsg: {
                receiver: '',
                words: ''
            },
            chat: {chat_room_id:''}
        },
        created: function () {
            init(AppKey, function (c) {
                console.log('receive: ',c);
                this.print(c.name + ": " + c.msg);
            }.bind(this));
        },
        methods: {
            print: function (str) {
                this.logs.push(str);
            },
            connect: function () {
                if (!this.name) alert('您得输入用户名');
                let that = this;
                $.ajax({
                    type: "POST",
                    headers: {appid:1,appsecret:"39b3567d0b8ac89c025b78beec26acb0"},
                    url: TokenUrl,
                    data: {name: this.name},
                    success(resp){
                        that.chat = resp.chat;
                        console.log('获取token：', resp);
                        connect(that.chat.token, function () {
                            console.log('连接成功');
                            join(that.chat.chat_room_id, function () {
                                that.isJoin = true;
                                console.log('加入聊天室成功！')
                            });
                        });
                    }
                });
            },
            join: function () {
                join(this.chat.chat_room_id);
            },
            send: function (type) {
                if (this.sendMsg.words) {
                    send(type, {
                        receiver: (1==type ? this.sendMsg.receiver : this.chat.chat_room_id) ,
                        content: {
                            name: this.chat.name,
                            avatar: this.chat.avatar,
                            msg: this.sendMsg.words.toString()
                        }
                    });
                    this.sendMsg.words = '';
                }
            }
        }
    });

    function print(str) {
        console.log(str);
    }

    function init(appKey, cb) {
        RongIMClient.init(appKey);

        RongIMClient.setConnectionStatusListener({
            onChanged: function (status) {
                switch (status) {
                    case RongIMLib.ConnectionStatus.CONNECTED:
                        print('链接成功');
                        break;
                    case RongIMLib.ConnectionStatus.CONNECTING:
                        print('正在链接');
                        break;
                    case RongIMLib.ConnectionStatus.DISCONNECTED:
                        print('断开连接');
                        break;
                    case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                        print('其他设备登录');
                        break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                        print('域名不正确');
                        break;
                    case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                        print('网络不可用');
                        break;
                }
            }
        });
        RongIMClient.setOnReceiveMessageListener({
            // 接收到的消息
            onReceived: function (message) {
                // 判断消息类型
                switch(message.messageType){
                    case RongIMClient.MessageType.TextMessage:
                        /*
                         显示消息方法：
                         消息里是 原生emoji
                         RongIMLib.RongIMEmoji.emojiToHTML(message.content.content);
                         */
                        var content = message.content.content;
                        try{
                            if (typeof content == "string") content = JSON.parse(content);
                            if (typeof content !== "object") return;
                            cb(content);
                        }catch ($ex) {
                            console.log($ex);
                        }
                        break;
                    case RongIMClient.MessageType.VoiceMessage:
                        /*
                         引入SDK并初始化请参考文档 http://www.rongcloud.cn/docs/web.html#声音库

                         api文档： http://www.rongcloud.cn/docs/api/js/VoiceMessage.html

                         var audio = message.content.content //格式为 AMR 格式的 base64 码
                         var duration = message.content.duration;

                         RongIMLib.RongIMVoice.preLoaded(audio,function(){
                         RongIMLib.RongIMVoice.play(audio,duration);
                         });
                         */
                        break;
                    case RongIMClient.MessageType.ImageMessage:
                        // message.content.content => 图片缩略图 base64。
                        // message.content.imageUri => 原图 URL。
                        break;
                    case RongIMClient.MessageType.DiscussionNotificationMessage:
                        // message.content.extension => 讨论组中的人员。
                        break;
                    case RongIMClient.MessageType.LocationMessage:
                        // message.content.latiude => 纬度。
                        // message.content.longitude => 经度。
                        // message.content.content => 位置图片 base64。
                        break;
                    case RongIMClient.MessageType.RichContentMessage:
                        // message.content.content => 文本消息内容。
                        // message.content.imageUri => 图片 base64。
                        // message.content.url => 原图 URL。
                        break;
                    case RongIMClient.MessageType.InformationNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.ContactNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.ProfileNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.CommandNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.CommandMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.UnknownMessage:
                        // do something...
                        break;
                    default:
                    // do something...
                }
            }
        });
    }

    function connect(token, cb) {
        if (!token) {
            print("token不能为空！");
            return;
        }

        RongIMClient.connect(token, {
            onSuccess: function (userId) {
                cb();
                print(userId + " 登录成功。");
            },
            onTokenIncorrect: function () {
                print('token无效');
            },
            onError: function (errorCode) {
                let info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.UNACCEPTABLE_PROTOCOL_VERSION:
                        info = '不可接受的协议版本';
                        break;
                    case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                        info = 'appkey不正确';
                        break;
                    case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                        info = '服务器不可用';
                        break;
                }
                print(info + " : " + errorCode);
            }
        });
    }

    function join(chatRoomId, cb, err) {
        if (!chatRoomId) return;

        RongIMClient.getInstance().joinChatRoom(chatRoomId, 100, {
            onSuccess: function () {
                // 加入聊天室成功。
                if (typeof cb == "function") cb();
            },
            onError: function (error) {
                // 加入聊天室失败
                if (typeof err == "function") err();
            }
        });
    }

    function getChatRoomInfo(chatRoomId, cb, err) {
        let order = RongIMLib.GetChatRoomType.REVERSE;// 排序方式。
        RongIMClient.getInstance().getChatRoomInfo(chatRoomId, 10, order, {
            onSuccess: function (chatRoom) {
                // chatRoom => 聊天室信息。
                // chatRoom.userInfos => 返回聊天室成员。
                // chatRoom.userTotalNums => 当前聊天室总人数。
                if (typeof cb == "function") cb();
            },
            onError: function (error) {
                // 获取聊天室信息失败。
                if (typeof err == "function") err();
            }
        });
    }

    /**
     *  发送消息
     * @param type
     * @param sendMsg
     * @param cb
     * @param err
     */
    function send(type, sendMsg, cb, err) {

        let s = sendMsg.content;
        let msg = new RongIMLib.TextMessage({content: s, extra: "ext"});

        RongIMClient.getInstance().sendMessage(type, sendMsg.receiver, msg, {
            onSuccess: function (message) {
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                if (typeof cb == "function") cb(message);
            },
            onError: function (errorCode, message) {
                let info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default :
                        info = "";
                        break;
                }
                console.log('发送失败:' + info);
                if (typeof err == "function") err(errorCode, info);
            }
        });
    }


</script>